<%--
  Created by IntelliJ IDEA.
  User: 猽
  Date: 2020/12/22
  Time: 15:59
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <title>客户列表</title>
    <%-- 引入css样式 --%>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/resources/layui/css/layui.css">
</head>
<body>
<form class="layui-form layui-form-pane">
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label">
                客户名称
            </label>
            <div class="layui-input-inline">
                <input type="text" class="layui-input" id="name" autocomplete="off">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">
                电话
            </label>
            <div class="layui-input-inline">
                <input type="text" class="layui-input" id="phone" autocomplete="off">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">
                性别
            </label>
            <div class="layui-input-inline">
                <select id="sex">
                    <option value="">性别</option>
                    <option value="1">男</option>
                    <option value="2">女</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">
                    公司
                </label>
                <div class="layui-input-inline">
                    <input type="text" class="layui-input" id="company" autocomplete="off">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">
                    状态
                </label>
                <div class="layui-input-inline">
                    <select id="deleted">
                        <option value="">状态</option>
                        <option value="1">有效</option>
                        <option value="2">无效</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">
                    业务员
                </label>
                <div class="layui-input-inline">
                    <select id="userId">
                        <option value="">业务员</option><!-- 业务员不能写死 后面用JS填充 -->
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <button class="layui-btn" id="searchBtn" type="button">查询</button>
                <button class="layui-btn layui-btn-primary" type="reset">重置</button>
            </div>
        </div>
    </div>
</form>
<hr>
<table id="dataTable" lay-filter="dataTableFilter"></table>
<%-- 头工具栏 --%>
<script type="text/html" id="headerBtns">
    <div class="layui-btn-group">
        <c:if test="${user.role == 2}">
            <button class="layui-btn layui-btn-sm" lay-event="add">
                <i class="layui-icon layui-icon-add-1"></i>
                添加客户
            </button>
        </c:if>
        <%-- 管理员权限      --%>
        <c:if test="${user.role == 1}">
            <button class="layui-btn layui-btn-sm" lay-event="setSalesman">
                <i class="layui-icon layui-icon-set"></i>
                分配业务员
            </button>
        </c:if>
    </div>
</script>


<script type="text/html" id="rowBtns">
    <div class="layui-btn-group">
        <c:if test="${user.role == 2}">
            <button class="layui-btn layui-btn-sm layui-btn-warm" lay-event="edit">
                <i class="layui-icon layui-icon-edit"></i>
                修改
            </button>
            <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="del">
                <i class="layui-icon layui-icon-delete"></i>
                删除
            </button>
            <button class="layui-btn layui-btn-sm" lay-event="visit">
                <i class="layui-icon layui-icon-release"></i>
                拜访
            </button>
        </c:if>
    </div>
</script>

<%--添加客户时的弹出层html页面--%>
<script type="text/html" id="editTpl">
    <form class="layui-form layui-form-pane" lay-filter="editFormFilter" style="margin-left: 20px;margin-top: 20px">
        <div class="layui-form-item">
            <label class="layui-form-label">姓名</label>
            <div class="layui-input-inline">
                <input type="text" name="name" class="layui-input" autocomplete="off" placeholder="客户名称"
                       lay-verify="required" lay-reqText="客户名称不能为空">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">电话</label>
            <div class="layui-input-inline">
                <input type="text" name="phone" class="layui-input" autocomplete="off" placeholder="手机号"
                       lay-verify="required|phone" lay-reqText="客户电话不能为空">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">性别</label>
            <div class="layui-input-inline" style="width: 210px">
                <input type="radio" name="sex" title="男" value="1" checked>
                <input type="radio" name="sex" title="女" value="2">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">公司</label>
            <div class="layui-input-inline">
                <input type="text" name="company" autocomplete="off" placeholder="客户公司" lay-verify="required"
                       lay-reqText="客户公司不能为空" class="layui-input">
            </div>
        </div>
        <button id="subBtn" type="button" lay-submit lay-filter="subBtnFilter" style="display: none"></button>
    </form>
</script>

<%--设置业务员的弹层模板--%>
<script type="text/html" ID="setSalesmanTpl">
    <form class="layui-form layui-form-pane" lay-filter="editFormFilter" style="margin-left: 20px;margin-top: 20px">
        <div class="layui-form-item">
            <label class="layui-form-label">业务员</label>
            <div class="layui-input-inline">
                <select id="editUserId" name="userId" lay-verify="required" lay-reqText="请选择业务员">
                    <option value="">业务员</option>
                </select>
            </div>
        </div>
        <button id="subBtn" type="button" lay-submit lay-filter="subBtnFilter" style="display: none"></button>
    </form>
</script>

<%--新增拜访记录的弹层记录模板--%>
<script type="text/html" ID="addVisitLogTpl">
    <form class="layui-form layui-form-pane" lay-filter="editFormFilter" style="margin-left: 20px;margin-top: 20px">
        <div class="layui-form-item">
            <label class="layui-form-label">客户</label>
            <div class="layui-input-inline">
                <%-- 存储客户ID --%>
                <input type="hidden" name="id">
                <%-- 存储客户名称 --%>
                <input type="text" class="layui-input" name="name" readonly/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">拜访时间</label>
            <div class="layui-input-inline" >
                <input type="text" readonly name="visitTime" id="visitTime" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item layui-form-text" style="width: 310px">
            <label class="layui-form-label">拜访内容</label>
            <div class="layui-input-block" >
                <textarea name="descp" class="layui-textarea"></textarea>
            </div>
        </div>
        <button id="subBtn" type="button" lay-submit lay-filter="subBtnFilter" style="display: none"></button>
    </form>
</script>


<script src="${pageContext.request.contextPath}/resources/layui/layui.js"></script>
<script>
    layui.use(['form', 'layer', 'jquery', 'table','laydate'], function () {
        let form = layui.form;
        let layer = layui.layer;
        let $ = layui.jquery;
        let table = layui.table;
        let laydate = layui.laydate;
        //项目根目录
        let cxt = "${pageContext.request.contextPath}";

        //初始化业务员
        function initSalesman() {
            $.get(cxt + "/user.do?service=salesmans", function (rs) {
                if (rs.code == 200) {
                    let data = rs.data;
                    let select = $("#userId");
                    let options = new Array();
                    for (let user of data) {
                        options.push("<option value='" + user.id + "'>" + user.realname + "</option>")
                    }
                    let option = options.join();
                    select.append(option);
                    //渲染下拉框
                    form.render("select");
                }
            })
        }

        initSalesman();

        //渲染表格
        let tabOpt = {
            id: "dataTableId",
            elem: "#dataTable",
            url: cxt + "/customer.do?service=page",
            page: true,
            toolbar: "#headerBtns",
            cols: [[
                {type: "checkbox", fixed: "left"},
                {title: "客户名", field: "name"},
                {title: "电话", field: "phone"},
                {title: "公司", field: "company"},
                {
                    title: "性别", field: "sex", templet: function (d) {
                        let sex = d.sex;
                        if (sex == 1) {
                            return "<b style='color:mediumvioletred'>男</b>";
                        } else if (sex == 2) {
                            return "<b style='color:lightseagreen'>女</b>";
                        }
                    }
                },
                {
                    title: "状态", field: "deleted", templet: function (d) {
                        let deleted = d.deleted;
                        if (deleted == 1) {
                            return "<b style='color:lightseagreen'>有效</b>";
                        } else if (deleted == 2) {
                            return "<b style='color:lightslategrey'>无效</b>";
                        }
                    }
                },
                {title: "业务员", field: "realname"},
                {title: "创建时间", field: "createTime"},
                {title: "删除时间", field: "deleteTime"},
                {title: "操作", toolbar: "#rowBtns", minWidth: 220, fixed: "right"},

            ]],
            parseData: function (rs) {
                return {
                    code: rs.code,
                    msg: rs.msg,
                    count: rs.data.count,
                    data: rs.data.data
                }
            },
            response: {
                statusCode: 200
            }
        };
        let tabIns = table.render(tabOpt);

        //搜索
        $("#searchBtn").click(function () {
            let name = $("#name").val();
            let phone = $("#phone").val();
            let sex = $("#sex").val();
            let company = $("#company").val();
            let deleted = $("#deleted").val();
            let userId = $("#userId").val();
            //表格重载
            tabIns.reload({
                where: {
                    name: name,
                    phone: phone,
                    sex: sex,
                    company: company,
                    userId: userId,
                    deleted: deleted
                }
            });
        });

        //表格头工具栏监听事件
        table.on("toolbar(dataTableFilter)", function (d) {
            let event = d.event;
            if (event == "add") {
                add();
            } else if (event == "setSalesman") {
                setSalesman();
            }
        });


        let layerOpt = {
            title: "编辑",
            type: 1,
            content: $("#editTpl").html(),
            area: ['360px', '390px'],
            btn: ['确认', '取消'],
            btnAlign: "c",
            yes: function (index, layero) {
                //触发提交按钮点击
                $("#subBtn").click();
            }
        };


        /**
         * 新增员工
         */
        function add() {
            let addOpt = {};
            Object.assign(addOpt, layerOpt);
            addOpt.success = function (layero, index) {
                //渲染表单
                form.render("radio");
                //表单的监听提交
                form.on("submit(subBtnFilter)", function (d) {
                    let formData = d.field;
                    //使用ajax提交数据
                    $.post(cxt + "/customer.do?service=add", formData, function (rs) {
                        layer.msg(rs.msg);
                        if (rs.code != 200) {
                            return false;
                        }
                        layer.close(index);//关闭弹层
                        $("#searchBtn").click();//刷新表格
                    })
                })
            }
            layer.open(addOpt);
        }

        /**
         * 设置客户的业务员
         */
        function setSalesman() {
            //1.获取选中的客户
            let status = table.checkStatus("dataTableId");
            let rowDatas = status.data;
            if (rowDatas.length == 0) {
                layer.msg("请先选中需要设置的客户！");
                return false;
            }
            let opt = {
                title: "设置业务员",
                type: 1,
                content: $("#setSalesmanTpl").html(),
                area: ['360px', '360px'],
                btn: ['确认', '取消'],
                btnAlign: 'c',
                success: function (layero, index) {
                    //获取所有的业务员 放入到select中
                    console.log("001");
                    let select1 = $("#userId");
                    let select2 = $("#editUserId");
                    //获取到搜索框中的业务员信息
                    let options = select1.html();
                    //将所有的业务员放入下拉框中
                    select2.html(options);
                    //更新渲染
                    form.render();
                    //表单的提交监听
                    console.log("002");
                    form.on("submit(subBtnFilter)", function (d) {
                        let formData = d.field;//业务员ID
                        //拿到所有的客户ID
                        console.log("003");
                        let cId = new Array();
                        for (let c of rowDatas) {
                            cId.push("cId=" + c.id);
                        }
                        //所有选中的客户的ID
                        let cIds = cId.join("&");

                        //使用ajax提交数据
                        $.post(cxt + "/customer.do?service=setSalesman&" + cIds, formData, function (rs) {
                            layer.msg(rs.msg);
                            if (rs.code != 200) {
                                return false;
                            }
                            layer.close(index);//关闭弹层
                            $("#searchBtn").click();//刷新表格
                        })

                    })
                },
                yes: function (index, layero) {
                    $("#subBtn").click();
                }
            };
            layer.open(opt);
        }


        //设置行工具栏监听事件
        table.on("tool(dataTableFilter)", function (d) {
            let event = d.event;
            let rowData = d.data;
            if (event == "edit") {
                update(rowData);
            } else if (event == "del") {
                del(rowData);
            } else if (event == "visit") {
                visit(rowData);
            }
        })

        /**
         * 修改数据
         * @param rowData
         */
        function update(rowData) {
            let editOpt = {};
            Object.assign(editOpt, layerOpt);
            editOpt.success = function (layero, index) {
                //为表单赋值
                form.val("editFormFilter", rowData);

                //重新渲染表单
                form.render();
                console.log(rowData.name + "1");
                //为表单设置提交监听
                form.on("submit(subBtnFilter)", function (d) {
                    console.log(rowData.phone + "2");
                    let formData = d.field;//没有ID 但是后台需要根据ID修改
                    formData.id = rowData.id;//行数据中的ID 赋给表单数据
                    $.post(cxt + "/customer.do?service=update", formData, function (rs) {
                        console.log("出现了吗");
                        layer.msg(rs.msg);
                        console.log(rs);
                        if (rs.code != 200) {
                            return false;
                        }
                        layer.close(index);//关闭弹层
                        $("#searchBtn").click();
                    })
                });
            }
            layer.open(editOpt);
        }


        function del(rowData) {
            let deleted = rowData.deleted;
            if (deleted == 2) {
                layer.msg("客户已删除!");
                return false;
            }
            layer.confirm("确定要删除该客户吗?", function (index) {
                $.get(cxt + "/customer.do?service=delete", {id: rowData.id}, function (rs) {
                    layer.msg(rs.msg);
                    if (rs.code != 200) {
                        return false;
                    }
                    layer.close(index);
                    $("#searchBtn").click();
                })
            })
        }

        /**
         * 新增拜访记录
         * @param rowData
         */
        function visit(rowData) {
            let visitOpt = {};
            Object.assign(visitOpt,layerOpt);
            visitOpt.content = $("#addVisitLogTpl").html();
            visitOpt.success = function (layero,index) {
                //为表单赋值
                form.val("editFormFilter",rowData);
                //渲染时间
                laydate.render({elem: "#visitTime"});
                //为表单设置提交监听
                form.on("submit(subBtnFilter)",function (d) {
                    let formData = d.field; //没有ID 的  但是后台需要根据ID 修改
                    $.post(cxt+"/customer.do?service=visit",formData,function (rs) {
                        layer.msg(rs.msg);
                        if (rs.code != 200){
                            return false;
                        }
                        layer.close(index);
                        $("#searchBtn").click();
                    })

                });
            }
            layer.open(visitOpt);

        }
    })
</script>

</body>
</html>

